import { Injectable } from '@nestjs/common';
import { Equal, Like, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly user: Repository<User>,
  ) {}

  create(createUserDto: CreateUserDto) {
    const data = new User();
    data.name = createUserDto.name;
    data.age = createUserDto.age;
    data.sex = createUserDto.sex;
    data.phone = createUserDto.phone;
    data.adress = createUserDto.adress;

    try {
      this.user.save(data);

      return '创建成功';
    } catch (error) {
      return {
        status: -1,
        msg: error,
      };
    }
  }

  findAll(query: { keyword: string }) {
    if (!query.keyword) {
      query.keyword = '';
    }

    return this.user.find({
      where: {
        name: Like(`%${query.keyword}%`),
      },
    });
  }

  findOne(name: string) {
    return this.user.find({
      where: {
        name: Equal(name),
      },
    });
  }

  update(id: string, updateUserDto: UpdateUserDto) {
    return this.user.update(id, updateUserDto);
  }

  remove(id: string) {
    return this.user.delete(id);
  }
}
